package com.tyqx.hashchainbiz;

// import com.alibaba.fastjson.JSON;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.tyqx.hashchainbean.module.NoHashValueJson;
import com.tyqx.hashchainbean.module.WxAccountFirmVerification;
import com.tyqx.hashchainbean.vo.MongoDbInfoVO;
import com.tyqx.hashchainbiz.service.NoHashValueJsonService;
import hashchainutil.common.EmptyUtils;
import hashchainutil.common.JsonUtil;
import org.bson.types.ObjectId;
import org.hyperledger.fabric.sdk.security.CryptoPrimitives;
import org.json.JSONObject;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Date;
import java.util.List;

@Component
public class SchedulerMongoDBAccountFirmVerification {
    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Resource
    private MongoTemplate mongoTemplate;

    @Resource
    private NoHashValueJsonService noHashValueJsonService;

    ///@Async
    //表示每隔秒
//    @Scheduled(fixedRate = 60 * 1000 * 10)
    @Transactional(rollbackFor = Exception.class)
    @Scheduled(fixedDelay = 1000 * 11)
    public void testTasks() throws Exception {
        System.out.println("wxAccountFirmVerification读取记录定时任务执行时间：" + dateFormat.format(new Date()));
        String collNameJl = "wxAccountFirmVerification";
        CryptoPrimitives suite = new CryptoPrimitives();
        suite.init();
        Aggregation aggregationJlS = Aggregation.newAggregation(Aggregation.sample(1));
        AggregationResults<MongoDbInfoVO> mongoDbInfoVOJlS = mongoTemplate.aggregate(aggregationJlS, collNameJl, MongoDbInfoVO.class);
        MongoDbInfoVO mongoDbInfoVOJlSUnique = mongoDbInfoVOJlS.getUniqueMappedResult();
        if (EmptyUtils.isNotEmpty(mongoDbInfoVOJlSUnique)) {
            List<NoHashValueJson> noHashValueJsonList = new ArrayList<>();
            List<WxAccountFirmVerification> wxAccountFirmVerificationList = (List<WxAccountFirmVerification>) mongoDbInfoVOJlSUnique.getInfoList();
            int size = wxAccountFirmVerificationList.size();
            for (int i = 0; i < size; i++) {
                WxAccountFirmVerification wxAccountFirmVerification = wxAccountFirmVerificationList.get(i);
                Date currentDate = new Date();
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date createTime = sdf.parse(sdf.format(currentDate));
                wxAccountFirmVerification.setCreateDate(createTime);
                wxAccountFirmVerification.setModifyDate(createTime);
                Gson gson = new GsonBuilder()
                        .setDateFormat("yyyy-MM-dd HH:mm:ss")
                        .create();
                JSONObject jsonObject = new JSONObject(gson.toJson(wxAccountFirmVerification));
                jsonObject = JsonUtil.getSortJson(jsonObject);
                String jztLogisticsStr = jsonObject.toString();

                NoHashValueJson noHashValueJson = new NoHashValueJson();
                noHashValueJson.setRecordJson(jztLogisticsStr);
                noHashValueJson.setHashTableName("wx_account_firm_verification");
                noHashValueJson.setUserName(wxAccountFirmVerification.getCreateId());
                byte[] hashBytes = suite.hash(jztLogisticsStr.getBytes());
                String hashValue = Base64.getEncoder().encodeToString(hashBytes);

                noHashValueJson.setHashValue(hashValue);

                noHashValueJson.setStatus(0);

                noHashValueJsonList.add(noHashValueJson);
            }
            Integer flag = noHashValueJsonService.insertNoHashValueJsonBatch(noHashValueJsonList);

            if (flag > 0) {
                Query removeQuery = new Query();
                String mongoDBId = mongoDbInfoVOJlSUnique.getId();
                ObjectId objectId = new ObjectId(mongoDBId);
                Criteria criteria = Criteria.where("_id").is(objectId);
                removeQuery.addCriteria(criteria);
                mongoTemplate.remove(removeQuery, MongoDbInfoVO.class, collNameJl);
            }
        }

        System.out.println("wxAccountFirmVerification读取记录定时任务结束时间：" + dateFormat.format(new Date()));

    }

}